package com.example.servlet;

import com.example.dao.StudentMapper;
import com.example.pojo.StuClass;
import com.example.pojo.Student;
import com.example.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UpdateStudentServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取表单数据
        String stu_name = request.getParameter("stu_name");
        int stu_no = Integer.parseInt(request.getParameter("stu_no"));
        int stu_id = Integer.parseInt(request.getParameter("stu_id"));
        String class_name = request.getParameter("class_name");
        //根据class_name，获取StuClass对象
        SqlSession sqlSession1 = MybatisUtils.getSqlSession();
        StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
        StuClass stuClass = mapper1.getClassByClassName(class_name);
        // 创建学生对象
        Student student = new Student();
        student.setStu_id(stu_id);
        student.setStu_name(stu_name);
        student.setClass_id(stuClass.getClass_id());
        student.setStu_no(stu_no);

        // 调用Dao层将学生数据更新到数据库
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

        studentMapper.updateStudent(student);
        sqlSession.commit();
        sqlSession.close();

        // 重定向到学生列表页面或其他页面
        response.sendRedirect("home.jsp");
    }
}
